import {connect} from 'react-redux'
import {createIncrementAction,createDecrementAction,createIncrementAsyncAction} from '../../redux/actions/count';
import React, { Component } from 'react'
class Count extends Component {
    mun = React.createRef()
    increment = ()=>{
        const {value} = this.mun.current
        this.props.add(Number(value))
    }
    decrement = ()=>{
        const {value} = this.mun.current
        this.props.sub(Number(value))
    }
    incrementIfOdd = ()=>{
        const {value} = this.mun.current
        if(this.props.count % 2 !== 0){
            this.props.add(Number(value))
        }
    }
    incrementAsync = ()=>{
        const {value} = this.mun.current
        this.props.addAsync(Number(value),500)
    }
    render() {
        const {count} = this.props
        return (
            <div>
                <h1>当前求和为：{count}</h1>
                <select ref={this.mun}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>&nbsp;
                <button onClick={this.increment}>+</button>&nbsp;
                <button onClick={this.decrement}>-</button>&nbsp;  
                <button onClick={this.incrementIfOdd}>当前求和为奇数加</button>&nbsp;  
                <button onClick={this.incrementAsync}>异步加</button>&nbsp;  
            </div>
        )
    }
}

const mapStateToProps = state => ({
    count: state.countData,
})
// 一般写法
// const mapDispatchToProps = dispatch =>({ 
//     add: value => dispatch(createIncrementAction(value)),
//     sub: value => dispatch(createDecrementAction(value)),
//     addAsync: (value,time) => dispatch(createIncrementAsyncAction(value, time)),
// })
// 精简写法
const mapDispatchToProps = {
    add:createIncrementAction,
    sub:createDecrementAction,
    addAsync: createIncrementAsyncAction,
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
    )(Count)